package flexconsoleparser;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.console.IHyperlink;
import org.eclipse.ui.console.IPatternMatchListenerDelegate;
import org.eclipse.ui.console.PatternMatchEvent;
import org.eclipse.ui.console.TextConsole;

/**
 * @author lizhiyu
 * 
 */
public class FlexConsolePatternMatchListener implements
	IPatternMatchListenerDelegate {

	private TextConsole fConsole;

	public FlexConsolePatternMatchListener() {
	}

	public void connect(TextConsole console) {
		fConsole = console;
		// System.out.println(console.getType());
	}

	public void disconnect() {
		fConsole = null;
	}

	protected TextConsole getConsole() {
		return fConsole;
	}

	/*
	 * when a console line match the regex pattern, we want to add a hyperlink on
	 * that filename
	 * 
	 * @see org.eclipse.ui.console.IPatternMatchListenerDelegate#matchFound(org.eclipse.ui.console.PatternMatchEvent)
	 */
	public void matchFound(PatternMatchEvent event) {
		// System.err.println("match! " + event.toString());
		// TextConsole con = (TextConsole) event.getSource();
		
		int offset = event.getOffset();
		int length = event.getLength();
		IDocument doc = getConsole().getDocument();
		try {
			String line = doc.get(offset, length);
			
			// parse error line to get file, line, column etc.
			FlexErrorLineParser parser = new FlexErrorLineParser();
			parser.parse(line);
			if (parser.find()) {
				// get the source file
				IPath path = Path.fromOSString(parser.getFileName());
				IFile file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
				
				// the file shall be found inside the workspace
				if (file != null) {
					// IHyperlink link = new FileLink(file, null, -1, -1, parser.getLineNo());
					IHyperlink link = new FlexFileHyperlink(file, null, 
						parser.getLineNumber(), parser.getColumnNumber());
					
					// only affect the file name
					length = length - 1 - parser.getMessage().length();
					
					// add hyperlink to console
					getConsole().addHyperlink(link, offset,	length);
				}
			}
		} catch (BadLocationException e) {
		}
	}
}
